<?php

class PackageController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/admin/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
		array('auth.filters.AuthFilter'),
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
		),
		array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
//		$examitempackage_ret = B2bExamItemToPackage::model()->findAllByAttributes(array("package_id" => $id));
//		$examitemid_arr = array();
//
//		if (!empty($examitempackage_ret)){
//			foreach ($examitempackage_ret as $item){
//				array_push($examitemid_arr, $item->exam_item_id);
//			}
//		}
//		$examitemclassify_ret = BasicExamItemClassify::model()->findAll();
//		$itemclassify_arr = array();
//		foreach ($examitemclassify_ret as $item) {
//			$itemclassify_arr[$item->id] = $item->item_name;
//		}
//		
//		$examitem_ret = BasicExamItem::model()->findAllByAttributes(array("id" => $examitemid_arr));
		$item_arr = array();
//		foreach ($examitem_ret as $item) {
//			if (!isset($item_arr[$itemclassify_arr[$item->item_id]])){
//				$item_arr[$itemclassify_arr[$item->item_id]] = array();
//			}
//			array_push($item_arr[$itemclassify_arr[$item->item_id]], $item);
//		}
//		echo "<pre>";
//		var_dump($item_arr);
//		echo "</pre>";
//		exit();
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'examitem_arr'=>$item_arr,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new B2bPackage;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['B2bPackage']))
		{
			$model->attributes=$_POST['B2bPackage'];
			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=new B2bPackage;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['B2bPackage']))
		{
			$model->attributes=$_POST['B2bPackage'];
			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$tran_ins = Yii::app()->db->beginTransaction();
		try{
			$this->loadModel($id)->delete();
			B2bExamItemToPackage::model()->deleteAllByAttributes(array("package_id" => $id));
			$tran_ins->commit();
		}catch (CException $e){
			$tran_ins->rollback();
		}
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('B2bPackage');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new B2bPackage('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['B2bPackage']))
		$model->attributes=$_GET['B2bPackage'];
		$this->render('admin',array(
			'model'=>$model,
		));
	}
	public function actionBindexamitems($id = 0)
	{
		$model=$this->loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if (isset($_POST['classify'])){
			$transaction = Yii::app()->db->beginTransaction();
			try{
				/*
				 * 1	wheather classify is empty
				 * 1.1	yes		do noting
				 * 1.2	no		save the item_id to the b2b_exam_item_to_package
				 * 2	if classify[-1] empty
				 * 2.1	yes		do nothing
				 * 2.2	no		save all the item_id which belong to the classify_id
				 */
				$old_arr = array();
				$old_itemtopackage_arr = B2bExamItemToPackage::model()->findAllByAttributes(array("package_id" => $_POST['package_id']));
				foreach ($old_itemtopackage_arr as $item){
					array_push($old_arr, $item->exam_item_id);
				}

				$update_arr = array();
				foreach ($_POST['classify'] as $key => $arr){
					foreach ($arr as $item){
						array_push($update_arr, $item);
					}
				}
				$dele_arr = array_diff($old_arr, $update_arr);
				$add_arr = array_diff($update_arr, $old_arr);
				$up_arr = array_intersect($old_arr, $update_arr);

				B2bExamItemToPackage::model()->deleteAllByAttributes(array("package_id" => $_POST['package_id'], "exam_item_id" => $dele_arr));
				foreach ($add_arr as $item){
					$item_package_ins = new B2bExamItemToPackage();
					$item_package_ins->exam_item_id = $item;
					$item_package_ins->package_id = $_POST['package_id'];
					$item_package_ins->create_at= date('Y-m-d H:i:s',time());
					$item_package_ins->update_at= date('Y-m-d H:i:s',time());
					$ret = $item_package_ins->save();
					//						var_dump($item_package_ins->errors);exit();
				}
				foreach ($up_arr as $item){
					$item_package_ins = B2bExamItemToPackage::model()->findByAttributes(array("package_id" => $_POST['package_id'], "exam_item_id" => $item));
					$item_package_ins->exam_item_id = $item;
					$item_package_ins->package_id = $_POST['package_id'];
					$item_package_ins->update_at= date('Y-m-d H:i:s',time());
					$item_package_ins->update();
				}
				$transaction->commit();
				$this->redirect(array('view','id'=>$model->id));
			}catch (Exception $e){
				$transaction->rollback();
			}
		}

		//得到一种套餐对应的体检项目
		$examitempackage_ret = B2bExamItemToPackage::model()->findAllByAttributes(array("package_id" => $id));
		$examitempackage_exit_arr = array();
		foreach ($examitempackage_ret as $examitempackage) {
			$examitempackage_exit_arr[$examitempackage->exam_item_id] = $examitempackage;
		}
		//得到体检项目大类
		$basicitemclassify_ret = BasicExamItemClassify::model()->findAll();
		//得到体检项目小项
		$basicitem_ret = BasicExamItem::model()->findAll();
		$basicitem_arr = array();
		/*
		 * array("大项目" => array(
		 * 							"小项目" => array(
		 * 											"flage" => true/false,
		 * 											"ins" => 小项目实体)))
		 */
		foreach ($basicitem_ret as $item) {
			if (isset($examitempackage_exit_arr[$item->id])){
				$basicitem_arr[$item->item_id][$item->id] = array("check"=>true, "ins" => $item);
			}else{
				$basicitem_arr[$item->item_id][$item->id] = array("check"=>false, "ins" => $item);
			}
		}
		$this->render('bindexamitems',array(
			'model'=>$model,
			'basicitemclassify'=>$basicitemclassify_ret,
			'basicitem'=>$basicitem_arr,
		));
	}
	/**
	 * 绑定体检中心
	 */
	public function actionBindcenters($id = 0) {

		if (isset($_POST['bingcenters'])) {
			$ret = B2bPackageToCenter::model()->bindcenters($_POST['id'],$_POST['bingcenters']);
			if(true === $ret){
				JSONHelper::echoJSON(true);
			}else{
				JSONHelper::echoJSON(false,$ret);
			}

		}
		$model = $this->loadModel($id);
		$centers = B2bPackageToCenter::model()->with(array("center"))->findAllByAttributes(array("package_id"=>$id));
		$this->render('bindcenters', array(
                'model' => $model,"centers"=>$centers
		));
	}
	/**
	 * 删除绑定的体检中心
	 */
	public function actionDelcenter(){
		if(!isset($_POST["id"])){
			JSONHelper::echoJSON(false,"非法请求");
		}
		$ret = B2bPackageToCenter::model()->deleteByPk($_POST["id"]);
		JSONHelper::echoJSON(TRUE,$_POST["id"]);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return B2bPackage the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=B2bPackage::model()->findByPk($id);
		if($model===null)
		throw new CHttpException(404,'请求的页面不存在');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param B2bPackage $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='b2b-package-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
